from binascii import a2b_hex, b2a_hex

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

from configs.load_config import load

SECRET_KEY = load()["SECRET_KEY"]


class Crypt:

    secret_key = SECRET_KEY.encode("utf-8")
    random_bytes = b"r\xefG\x02t\xc9\x91^\x8b$-\x90\xb0\xee\xb5\xa6"

    @classmethod
    def encrypt(cls, value):
        crypto = AES.new(cls.secret_key, AES.MODE_OFB, cls.random_bytes)
        data = pad(value.encode("utf-8"), AES.block_size, style="x923")
        encrypt_data = b2a_hex(crypto.encrypt(data)).decode("utf-8")
        return encrypt_data

    @classmethod
    def decrypt(cls, value):
        crypto = AES.new(cls.secret_key, AES.MODE_OFB, cls.random_bytes)
        data = crypto.decrypt(a2b_hex(value))
        decrypt_data = unpad(data, AES.block_size, style="x923").decode()
        return decrypt_data

    def __new__(cls, *args, **kwargs):
        """强制使用以类方法调用f"""
        return cls

    def __call__(self, *args, **kwargs):
        """兼容原实例化写法"""
        return self


def decrypt_pw(auth_config):
    my_crypt = Crypt()
    try:
        if "password" in auth_config:
            auth_config["password"] = my_crypt.decrypt(auth_config["password"])
        elif isinstance(auth_config, list) and len(auth_config) > 2:
            auth_config[1] = my_crypt.decrypt(auth_config[1])
    except Exception:  # noqa
        pass
    return auth_config


if __name__ == "__main__":
    my_Crypt = Crypt()
    encrypt_value = my_Crypt.encrypt("adp@123")
    print(encrypt_value)
    decrypt_value = my_Crypt.decrypt("cf1a49baabe891a93619b65802a34839")
    print(decrypt_value)
